package com.ssi.mrms.action;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.ssi.mrms.model.Msg;
import com.ssi.mrms.utils.CaptchaUtils;

public class BaseAction extends ActionSupport implements ServletRequestAware ,ServletResponseAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4502399782785204808L;
	
	private HttpServletRequest request;
	private HttpServletResponse response;

	private static WebApplicationContext context = null;
	public static final String CAPTCHA_KEY_SEND_MAIL = "captcha_key_send_mail";
	private static final String REPORT_TEMPLATE_PATH = "report/";
	public static final String userLogin = "admin";
	private static final Logger logger = Logger.getLogger(BaseAction.class);
	private Msg msg = null;
	
	static {
		context = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
	}

	@SuppressWarnings("unchecked")
	public static <T> T lookupBean(Class<T> clazz, String beanId) {
		return (T) context.getBean(beanId);
	}

	public byte[] generateExcelToByte(final String xlsTemplateFileName, final Map<String, Object> beans) {
		logger.info("exportExcel start file name " + xlsTemplateFileName);
		XLSTransformer transformer = null;
		Workbook workbook = null;
		try (InputStream in = CaptchaUtils.class.getClassLoader().getResourceAsStream(
				REPORT_TEMPLATE_PATH + xlsTemplateFileName);
				ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
			transformer = new XLSTransformer();
			workbook = transformer.transformXLS(in, beans);
			if (workbook != null) {
				workbook.write(bos);
			}
			return bos.toByteArray();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		logger.info("exportExcel success..");
		return new byte[0];

	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	public static String getUserlogin() {
		return userLogin;
	}

	public Msg getMsg() {
		return msg;
	}

	public void setMsg(Msg msg) {
		this.msg = msg;
	}



	
}
